import Vue from 'vue'
import VueRouter from 'vue-router'
import {
  Toast
} from 'vant';

Vue.use(Toast);
const Home = () => import("@/views/Home.vue")
const MyPopUp = () => import("@/views/MyPopUp.vue")
const Topic = () => import("@/views/Topic.vue")
const Category = () => import("@/views/Category.vue")
const Cart = () => import("@/views/Cart.vue")
const User = () => import("@/views/User.vue")
const ProductDetail = () => import("@/views/ProductDetail.vue")
const CategoryList = () => import("@/views/CategoryList.vue")


Vue.use(VueRouter)
// 解决Vue-Router升级导致的Uncaught(in promise) navigation guard问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}
const routes = [{
    path: '/',
    //路由重定向
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home,
    meta: {
      isShowTabBar: true
    },
    //子路由，弹出层,路径不需要 / 
    children: [{
      path: 'popup',
      name: 'MyPopUp',
      component: MyPopUp,
    }]
  },
  {
    path: '/topic',
    name: 'Topic',
    component: Topic,
    meta: {
      isShowTabBar: true
    }
  },
  {
    path: '/cart',
    name: 'Cart',
    component: Cart,
    meta: {
      isShowTabBar: true
    }
  },
  {
    path: '/category',
    name: 'Category',
    component: Category,
    meta: {
      isShowTabBar: true
    }
  },
  {
    path: '/user',
    name: 'User',
    component: User,
    meta: {
      isShowTabBar: true
    }
  },
  {
    path: '/productdetail',
    name: 'ProductDetail',
    component: ProductDetail
  },
  {
    path: '/categorylist',
    name: 'CategoryList',
    component: CategoryList
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由拦截 ：导航守卫（前置导航守卫和后置导航守卫）
// 前置导航守卫 to即将到达的路由， from 当前要离开的路由，
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('token')
  if (to.path == '/cart') {
    if (token) {
      next() //这个next 只针对去往cart
    } else {
      Vue.prototype.$toast('请先登录');
      setTimeout(() => {
        next({
          name: 'User'
        })
      }, 1000)
    }
    return
  }
  next() //针对所有路由
})
export default router